package api

import (
	"go-eth-tracker/dao"
	"go-eth-tracker/models"
	"sync"
	"time"
)

type Context struct {
	Merchants map[string]*MerchantContext
	MssqlDao  *dao.MssqlDao
	merchantMU sync.Mutex
}

type MerchantContext struct {
	LastTime time.Time
	Mer      *models.Merchant
}

func (ctx *Context) GetMerchant(merchantId string) *models.Merchant {
	ctx.merchantMU.Lock()
	defer ctx.merchantMU.Unlock()
	if m, ok := ctx.Merchants[merchantId]; ok && time.Since(m.LastTime).Seconds() < 30 {
		return m.Mer
	}

	m := ctx.MssqlDao.GetMerchant(merchantId)
	if m != nil {
		ctx.Merchants[merchantId] = &MerchantContext{LastTime: time.Now(), Mer: m}
		return m
	}

	return nil
}
